package com.hmdp;

import com.hmdp.entity.Shop;
import com.hmdp.service.impl.ShopServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisIdWork;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

@SpringBootTest
class HmDianPingApplicationTests {
    @Autowired
    private ShopServiceImpl shopService;
    @Autowired
    private CacheClient cacheClient;
    @Autowired
    private RedisIdWork redisIdWork;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //@Test
    void testSave() {
        Shop shop = shopService.getById(1L);
        Long id = shop.getId();
        cacheClient.setLogicalExpire(CACHE_SHOP_KEY+id,shop, 10L, TimeUnit.MINUTES);
    }
    //@Test
    void testIdWork() {
        for (int i = 0; i < 1; i++) {
            long id = redisIdWork.nextId("order");
            System.out.println(id);
        }
    }

    /**
     * 将店铺下信息按照商户类型分组，类型相同的作为一组，存入geo集合中，
     * 为后续使用redis获得距离信息做准备
     */
    //@Test
    void loadShopData(){
        //查询店铺信息
        List<Shop> list = shopService.list();
        //把店铺信息按照typeId分组，一致放在同一个集合里面
        //Map<Long, List<Shop>> map = list.stream().collect(Collectors.groupingBy(Shop::getTypeId()));
        Map<Long, List<Shop>> map = list.stream().collect(Collectors.groupingBy(shop -> shop.getTypeId()));
        //分批写入redis
        for (Map.Entry<Long, List<Shop>> entry : map.entrySet()) {
            //3.1获取类型
            Long typeId = entry.getKey();
            String key="shop:geo:"+typeId;
            //3.2获取同类型店铺集合
            List<Shop> shops = entry.getValue();
            for(Shop shop:shops) {
                Double x = shop.getX();
                Double y = shop.getY();
                Long id = shop.getId();
                //3.3存入redis
                stringRedisTemplate.opsForGeo().add(key, new Point(x, y),id.toString());
            }
        }
    }



}
